<script setup>
import { updateReaderAPI } from '@/api/reader';
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';

// 组件通信
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  readerData: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits([
  'update:modelValue',
  'success'
]);

// 表单数据
const formData = ref({ ...props.readerData });

// 监听readerData变化，更新表单数据
watch(() => props.readerData, (newVal) => {
  formData.value = { ...newVal };
}, { deep: true });

// 关闭对话框
const closeDialog = () => {
  emit('update:modelValue', false);
};

// 提交表单
const submitForm = async () => {
  try {
    const res = await updateReaderAPI(formData.value);
    if(res.data.code === 1) {
      ElMessage.success(res.data.msg);
      emit('success'); // 通知父组件刷新列表
      closeDialog();
    } else {
      ElMessage.error(res.data.msg || '更新失败');
    }
  } catch (error) {
    ElMessage.error('请求失败');
  }
};
</script>

<template>
  <el-dialog
    :model-value="props.modelValue"
    title="编辑读者信息"
    width="600px"
    :close-on-click-modal="false"
    @update:model-value="val => emit('update:modelValue', val)"
    @closed="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="卡号" prop="card">
        <el-input v-model="formData.card" placeholder="请输入读者卡号" clearable />
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" clearable />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name" placeholder="请输入读者姓名" clearable />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号" clearable />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" clearable />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>